/**
 * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
 * This file is part of CSipSimple.
 *
 *  CSipSimple is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  If you own a pjsip commercial license you can also redistribute it
 *  and/or modify it under the terms of the GNU Lesser General Public License
 *  as an android library.
 *
 *  CSipSimple is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with CSipSimple.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.cloudptt.api.product.battery;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

import com.cloudptt.api.product.log.Log;

/**
 * 电量管理
 * @author TP
 *
 */
public class BatteryBroadcast extends BroadcastReceiver {

	private static final String THIS_FILE = "BatteryBroadcast";

	private Context ctx = null;
	private Batteryistener lister = null;
	private int batterValue = 100;
//	private SysConfig sysConfig = null;


	public BatteryBroadcast(Context ctx,Batteryistener lister) 
	{
		Log.i(THIS_FILE, "BatteryBroadcast");
		this.ctx = ctx;
		this.lister = lister;
//		this.sysConfig = sysConfig;
		this.ctx.registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_LOW));
	}

	@Override
	public void onReceive(final Context context, final Intent intent) 
	{
		String action = intent.getAction();
		if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
			int value = getBatteryValue(intent);
			Log.i(THIS_FILE, "BatteryBroadcast onReceive value = " + value);
			if(batterValue == value
					&& value > 15)
			{
				return;
			}
			batterValue = value;
			if(lister != null)
			{
				lister.BatteryChange(batterValue);
			}
		} 
	}
	
	private int getBatteryValue(Intent intent)
	{
		int value = 100;
		if(intent == null)
		{
			return value;
		}
		value=gtBatteryValue(intent);
		return value;
	}
	
	private int gtBatteryValue(Intent intent)
	{
		int current=intent.getExtras().getInt("level");//鑾峰緱褰撳墠鐢甸噺
		int total=intent.getExtras().getInt("scale");//鑾峰緱鎬荤數閲�

		return current*100/total;
	}
	
	public int getBatterValue() 
	{
		Intent intent = ctx.registerReceiver(null,  
                        new IntentFilter(Intent.ACTION_BATTERY_CHANGED)) ;
		
		return getBatteryValue(intent);
	}

	public void clearResource()
	{
		Log.d(THIS_FILE, "NetWorkBroadcast clearResource");
		this.ctx.unregisterReceiver(this);
		this.ctx = null;
		this.lister = null;
	}
}
